<template>
  <div>
    <div>
      <el-form class="login" ref="formRef" :model="loginUser" :rules="rules" label-width="86px">
        <h3>登录</h3>
        <el-form-item label="用户名" prop="username">
          <el-input
              v-model="loginUser.username"
              placeholder="请输入用户名"
              prefix-icon="user"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
              v-model="loginUser.password"
              type="password"
              placeholder="请输入密码"
              prefix-icon="lock"
          ></el-input>
        </el-form-item>
        <el-form-item label>
          <el-button
              type="primary"
              class="w100p"
              @click="doLogin"
          >登录
          </el-button>
        </el-form-item>
        <div class="txt-r">
          <router-link to="/register">没有账号？去注册</router-link>
        </div>
      </el-form>
    </div>
  </div>
</template>
<script setup lang="ts">
import {useRouter} from 'vue-router';
import {login,getPermission} from '@/api';
import {useUserStore} from '@/store/user';
import {ref, reactive, computed} from 'vue'
import type {User} from '@/types';
import {storage} from '@/utils/storage.ts'

const router = useRouter();
const userStore = useUserStore();
const {setUserCache} = userStore;
const loginUser = reactive<User>({
  email: "", username: '', password: ''
});

const formRef = ref();

const rules = computed(() => {
  return {
    username: [
      {
        required: true,
        message: '请输入用户名',
        trigger: ["change", "blur"],
      }
    ],
    password: {
      required: true,
      min: 4,
      message: '密码error',
      trigger: ["change", "blur"],
    },
  }
});

function doLogin() {
  formRef.value.validate(async (valid: any) => {
    if (!valid) return;
    try {
      const res = await login({user: loginUser});
      setUserCache(res.data);
      const permission = await getPermission();
      storage("navlist").set(JSON.stringify(permission.data.permissionList))
      await router.push({name: 'Home'});
    } catch (error) {
    }
  });
}
</script>
<style lang="scss">
.login {
  width: 480px;
  margin: 200px auto 0;
  text-align: center;
}
</style>

